package com.tledu.student_manager.controller;

import com.alibaba.fastjson.JSONObject;
import com.tledu.student_manager.dao.UserDao;
import com.tledu.student_manager.exception.CustomException;
import com.tledu.student_manager.model.User;
import com.tledu.student_manager.service.UserService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@WebServlet("/user")
public class UserServlet extends HttpServlet {
    private UserService userService;

    @Override
    public void init() throws ServletException {
        super.init();
        this.userService = new UserService(new UserDao());
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 获取用户数据
        try {
            List<User> list = userService.list();
            req.setAttribute("list", list);
            req.getRequestDispatcher("/WEB-INF/view/user.jsp").forward(req, resp);
        } catch (CustomException e) {
            e.printStackTrace();
            req.setAttribute("msg", e.getMessage());
            req.getRequestDispatcher("/error").forward(req, resp);
        }
    }

    @Override
    protected void doDelete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        try {
            userService.delete(new Integer(req.getParameter("id")));
            // 给前端也给响应
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("code", 200);
            jsonObject.put("success", true);
            jsonObject.put("msg", "删除成功");
            resp.setContentType("application/json;charset=utf-8");
            resp.getWriter().println(jsonObject.toJSONString());
        } catch (CustomException e) {
            e.printStackTrace();
            req.setAttribute("msg", e.getMessage());
            req.getRequestDispatcher("/error").forward(req, resp);
        }
    }
}
